﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Web;
using System.Text;
using System.Xml;

namespace Sherwood.Content.Contracts
{
    /// <summary>
    /// Wraps a RESTful WCF client to an <see cref="IXmlUpdateService"/>.
    /// </summary>
    public class UpdateServiceClient : IXmlUpdateClient, IDisposable
    {
        private readonly IXmlUpdateService _channel;
        private readonly WebChannelFactory<IXmlUpdateService> _channelFactory;

        public UpdateServiceClient(string serviceUri)
        {
            _channelFactory = new WebChannelFactory<IXmlUpdateService>();
            _channelFactory.Endpoint.Binding = new WebHttpBinding();
            _channelFactory.Endpoint.Address = new EndpointAddress(serviceUri);
            _channelFactory.Endpoint.Behaviors.Add(new WebHttpBehavior());

            _channel = _channelFactory.CreateChannel();
        }

        public void UpdateRecords(updateRecordsRequest request)
        {
            var stream = _channel.UpdateRecords(request.GetAsMemoryStream());
            string result;
            using (var streamReader = new StreamReader(stream))
                result = streamReader.ReadToEnd();

            if (!result.StartsWith("<success"))
                throw new Exception("Method failed with response " + result);
        }

        public void Dispose()
        {
            _channelFactory.Close();
        }

        public Stream UpdateRecords(Stream xml)
        {
            return _channel.UpdateRecords(xml);
        }

        public Stream RebuildSearchIndex(string client)
        {
            throw new NotImplementedException();
        }
    }
}
